package com.komorebi.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.komorebi.common.Const;
import com.komorebi.common.Result;
import com.komorebi.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;

@Slf4j
@RestController
public class AuthController extends BaseController{

    @Autowired
    Producer producer;

    //获取验证码base64
    @GetMapping("/captcha")
    public Result captcha() throws IOException {
        //设置图片Key,用于redis存取
        String key = UUID.randomUUID().toString();
        //生成验证码中的文本
        String code = producer.createText();
        log.info("验证码文本：{}",code);
        //通过code生成图片
        BufferedImage image = producer.createImage(code);
        //创建字节输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",outputStream);
        //创建base64对象
        BASE64Encoder encoder = new BASE64Encoder();
        //设置base64固定前缀
        String str = "data:image/jpeg;base64,";
        //拼接base64字符串
        String base64Img = str + encoder.encode(outputStream.toByteArray());

        //存储到redis中
        //前两个参数共同确定一个code,例如：user:id
        redisUtil.hset(Const.CAPTCHA_KEY,key,code,120);
        log.info("验证码 -- {} - {}", key, code);
        //返回的json数据内包含多个信息时，可以使用MapUtil.builder()
        return Result.success(
                MapUtil.builder()
                        .put("token",key)
                        .put("captchaImg",base64Img)
                        .build()
        );
    }
    @GetMapping("/sys/userInfo")
    public Result getUserInfo(Principal principal){
        //principal.getName() == SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()
        //principal.getName() == SecurityContextHolder.getContext().getAuthentication().getName

        String username = principal.getName();
        SysUser sysUser = sysUserService.getByUserName(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        return Result.success(MapUtil.builder()
                .put("id",sysUser.getId())
                .put("username",username)
                .put("avatar",sysUser.getAvatar())
                .build()
        );
    }
}
